// <com.woyouqiu.Copyright>
// --------------------------------------------------------------
// <copyright>上海有求网络科技有限公司 2015</copyright>
// <Solution>MyCompany.MyProject</Solution>
// <Project>MyCompany.MyProject.Core</Project>
// <FileName>ProductCategoryDomainService.cs</FileName>
// <CreateTime>2017-04-21 17:19</CreateTime>
// <Author>何苗</Author>
// <Email>hemiao@woyouqiu.com</Email>
// <log date="2017-04-21 17:19" version="00001">创建</log>
// --------------------------------------------------------------
// </com.woyouqiu.Copyright>

using System.Linq;
using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.UI;
using Vecen.BangChuang.BangChuang.Products;

namespace Vecen.BangChuang.BangChuang.DomainServices.Products
{
    public class ProductCategoryDomainService : BangChuangDomainServiceBase
    {
        private readonly IRepository<ProductCategory> _categoriesRepository;
        private readonly IRepository<Product> _productRepository;

        public ProductCategoryDomainService(IRepository<ProductCategory> categoriesRepository,
            IRepository<Product> productRepository)
        {
            _categoriesRepository = categoriesRepository;
            _productRepository = productRepository;
        }

        /// <summary>
        /// 删除商品分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            if (_productRepository.GetAll().Any(c => c.CategoryId == id))
            {
                throw new UserFriendlyException("请求失败!", "商品分类已被使用,无法删除!");
            }
            if (_categoriesRepository.GetAll().Any(c => c.ParentId == id))
            {
                throw new UserFriendlyException("请求失败!", "商品分类已被使用,无法删除!");
            }

            await _categoriesRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 获得指定类别的商品数量
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public Task<int> GetProductCountByCategoryIdAsync(int categoryId)
        {
            return _productRepository.CountAsync(c => c.CategoryId == categoryId);
        }
    }
}